import { defineStore } from 'pinia'
import { store } from '@/store'
import { constantRoutes } from '@/router'

import { AppRouteType, AppDynamicRouteType } from '@/router/types'
import { Menu } from '@/api/auth/types'

const modules = import.meta.glob('../../views/**/**.vue')
const Layout = () => import('@/views/layout/index.vue')

/**
 * 通过角色决定当前用户是否有权限
 * @param roles
 * @param route
 */
const hasPermission = (roles: string[], route: AppRouteType) => {
  // 写死的动态权限在meta: roles: ['admin'] }  如果没有写则直接返回true
  if (route.meta && route.meta.roles) {
    return roles.some((role) => {
      if (route.meta?.roles !== undefined) {
        return (route.meta.roles as string[]).includes(role)
      }
    })
  }
  return true
}

 
// 加载路由
const loadView = (view: string) => {
  return modules[`../../views/${view}.vue`]
}

/**
 * 没问题
 * 通过递归格式化菜单路由 (配置项规则：https://panjiachen.github.io/vue-element-admin-site/zh/guide/essentials/router-and-nav.html#配置项)
 * @param routes
 */
export function filterAsyncRoutes(routes: Menu[]) {
  const res: AppRouteType[] = []
  routes.forEach((route) => {
    const tmp:AppRouteType = {
      path: route.path,
      name: route.name,
      component: route.component === 'Layout' ? Layout:loadView(route.component), // 这里的判断很重要
      meta: { title: route.title, icon: route.icon, buttons: route.buttons },
      children: (route.children && route.children.length>0)?filterAsyncRoutes(route.children):[]
    }
    res.push(tmp)
  })
  return res
}

// setup
// 权限存储 pinia
export const usePermissionStore = defineStore('permission', () => {
  // 所有路由
  const routes = ref<AppRouteType[]>([])

  // 固定路由加动态路由拼接在一起
  function setRoutes(newRoutes: AppRouteType[]) {
    routes.value = constantRoutes.concat(newRoutes)
  }

  // 根据接口数据拼接动态路由
  function generateDynamicRoutes(menus: Menu[]) {
    return new Promise<AppRouteType[]>((resolve, reject) => {
      const accessedRoutes = filterAsyncRoutes(menus)
      setRoutes(accessedRoutes) // Todo: 内部拼接constantRoutes，所以查出来的菜单不用包含constantRoutes
      resolve(accessedRoutes)
    })
  }

  return { routes, setRoutes, generateDynamicRoutes }
})

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
